package com.example.lcode.binary;

import java.util.Arrays;

/**
 *  思路
 *  由小推大
 *  Math.max （房屋1的最小半径、房屋2的最小半径、房屋的3的最小半径）
 */
public class Question475 {

    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int maxn = Integer.MIN_VALUE;
        for (int i = 0; i < houses.length; i++) {
            maxn = Math.max(maxn, findRadius(heaters, 0, heaters.length - 1, houses[i]));
        }
        return maxn;
    }

    private int findRadius(int[] heaters, int left, int right, int target) {
        if (left > right) {
            if (left == 0) {
                return Math.abs(heaters[left] - target);
            }
            return  Math.abs(heaters[right] - target);
        }
        int mid = (left + right) / 2;
        if (heaters[mid] == target) {
            return 0;
        } else if (mid != heaters.length - 1
                && heaters[mid] < target && heaters[mid + 1] > target) {
            return Math.min(Math.abs(heaters[mid] - target), Math.abs(heaters[mid + 1] - target));
        } else if (left < mid && heaters[mid] > target) {
            return findRadius(heaters, left, mid, target);
        } else if (right > mid && heaters[mid] < target){
            return findRadius(heaters, mid + 1, right, target);
        } else {
            return Math.min(Math.abs(heaters[left] - target), Math.abs(heaters[right] - target));
        }
    }

    public static void main(String[] args) {
        Question475 question475 = new Question475();
        int []house = {1,2,3,5,15};
        int []arr = {2,30};
        int radius = question475.findRadius(house, arr);
        System.out.println(radius);
    }

}
